<template>
  <div class="dashboard">
    <!-- 顶部欢迎语 -->
    <div class="header">
      <h2>Welcome！</h2>
      <p>追风赶月莫等闲，平芜尽处是春山</p>
    </div>

    <!-- 数据卡片 -->
    <div class="cards"> 
      <div class="card" v-for="(item, index) in cardData" :key="index" @click="handleCardClick(item)">
        <div class="icon" :style="{ backgroundColor: item.color }">
          <i :class="item.icon"></i>
        </div>
        <div class="text">
          <span>{{ item.label }}：</span>
          <strong>{{ item.value }}</strong>
        </div>
      </div>
    </div>

    <!-- 主要图表区域 -->
    <div class="charts">
      <!-- 任务统计 -->
      <div class="chart-item">
        <div class="chart-header">
          <h3>任务统计</h3>
          <div class="chart-controls">
            <span @click="updateTaskChart('7days')" :class="{ active: currentTaskPeriod === '7days' }">最近7天</span>
            <span @click="updateTaskChart('30days')" :class="{ active: currentTaskPeriod === '30days' }">最近30天</span>
            <span @click="updateTaskChart('1year')" :class="{ active: currentTaskPeriod === '1year' }">最近1年</span>
          </div>
        </div>
        <div ref="taskChart" class="chart"></div>
      </div>

      <!-- 工单实时进度 -->
      <div class="chart-item">
        <div class="chart-header">
          <h3>工单实时进度</h3>
          <el-button type="primary" size="small" @click="refreshTable">刷新</el-button>
        </div>
        <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ background: '#f5f7fa' }">
          <el-table-column fixed type="index" label="序号" width="60" />
          <el-table-column prop="produceCode" label="生产编号" width="150" />
          <el-table-column prop="produceName" label="生产订单名称" width="150" />
          <el-table-column prop="produceType" label="生产状态" width="150">
            <template v-slot="scope">
              <el-tag
                v-if="scope.row.produceType == 0"
                type="warning"
                effect="light"
                style="background-color: #fffbe6; color: #faad14; border: none;"
              >
                待发布
              </el-tag>
              <el-tag
                v-if="scope.row.produceType == 1"
                type="info"
                effect="light"
                style="background-color: #e6f7ff; color: #1890ff; border: none;"
              >
                进行中
              </el-tag>
              <el-tag
                v-if="scope.row.produceType == 2"
                type="success"
                effect="light"
                style="background-color: #f6ffed; color: #52c414; border: none;"
              >
                已完成
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="produceNum" label="产品数量" width="120" />
          <el-table-column prop="finishProduceNum" label="已生产数量" width="120" />
          <el-table-column label="生产完整度" width="180">
            <template #default="scope">
              <div class="progress-container">
                <div class="progress-bar" :style="{
                  width: scope.row.produceNum > 0 ?
                    Math.round((scope.row.finishProduceNum / scope.row.produceNum) * 100) + '%' : '0%',
                  backgroundColor: getProgressColor(scope.row.finishProduceNum / scope.row.produceNum)
                }">
                  {{ scope.row.produceNum > 0 ?
                    Math.round((scope.row.finishProduceNum / scope.row.produceNum) * 100) + '%' : '0%' }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            @current-change="handlePageChange"
            :current-page="page.Index"
            :page-size="page.Size"
            :total="page.totalcount"
            layout="prev, pager, next"
            background
          />
        </div>
      </div>

      <!-- 工序不合格比例 -->
      <div class="chart-item">
        <div class="chart-header">
          <h3>工序不合格比例</h3>
          <el-select v-model="selectedProcess" size="small" @change="updateProcessChart">
            <el-option label="全部工序" value="all"></el-option>
            <el-option label="印花装饰" value="印花装饰"></el-option>
            <el-option label="退火处理" value="退火处理"></el-option>
            <el-option label="高温固化" value="高温固化"></el-option>
            <el-option label="切割修边" value="切割修边"></el-option>
            <el-option label="原料配比与混合" value="原料配比与混合"></el-option>
          </el-select>
        </div>
        <div ref="processChart" class="chart"></div>
      </div>

      <!-- 生产质量统计 -->
      <div class="chart-item">
        <div class="chart-header">
          <h3>生产质量统计</h3>
          <div class="chart-controls">
            <span @click="updateQualityChart('7days')" :class="{ active: currentPeriod === '7days' }">最近7天</span>
            <span @click="updateQualityChart('30days')" :class="{ active: currentPeriod === '30days' }">最近30天</span>
            <span @click="updateQualityChart('1year')" :class="{ active: currentPeriod === '1year' }">最近1年</span>
          </div>
        </div>
        <div ref="qualityChart" class="chart"></div>
      </div>
    </div>

    <!-- 快捷操作区域 -->
    <div class="quick-access">
      <h3>快捷操作</h3>
      <div class="icons">
        <div class="icon-box" v-for="(item, index) in quickActions" :key="index" @click="handleQuickAction(item)">
          <div class="icon" :style="{ backgroundColor: item.color }">
            <i :class="item.icon"></i>
          </div>
          <div class="label">{{ item.label }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref, reactive } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage } from 'element-plus';
import router from '@/router';

const tableData = ref([])
//产线向后端传参
const page = reactive({
    Index: 1,
    Size: 3,
    totalcount: 0
})

// 卡片数据
const cardData = ref([
  { label: '计划数量', value: 322, icon: 'fas fa-file-alt', color: '#1890ff' },
  { label: '工单数量', value: 122, icon: 'fas fa-clipboard', color: '#f5222d' },
  { label: '任务数量', value: 322, icon: 'fas fa-tasks', color: '#faad14' },
  { label: '产品入库', value: 33, icon: 'fas fa-file-invoice', color: '#722ed1' }
])

// 快捷操作数据
const quickActions = ref([
  { label: 'BOM', icon: 'fas fa-plus-circle', color: '#1890ff' },
  { label: '物料申请单', icon: 'fas fa-chart-bar', color: '#52c414' },
  { label: '客户管理', icon: 'fas fa-cogs', color: '#722ed1' },
  { label: '供应商管理', icon: 'fas fa-check-circle', color: '#faad14' },
  { label: '生产工单', icon: 'fas fa-user-friends', color: '#f5222d' },
  { label: '计划排程', icon: 'fas fa-cog', color: '#13c2c2' },
  { label: '物料采购单', icon: 'fas fa-folder-open', color: '#722ed1' },
  { label: '物料入库', icon: 'fas fa-database', color: '#fa541c' },
  { label: '物理出库', icon: 'fas fa-file-alt', color: '#722ed1' },
  { label: '质检统计分析', icon: 'fas fa-file-invoice', color: '#faad14' },
  { label: '订单管理', icon: 'fas fa-file-alt', color: '#1890ff' },
])

//仓库显示
const GetProducetion = () => {
    axios.get('/api/ProductionModules/GetProducetion', { params: page }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.totalPage
            page.totalcount = res.data.totalcount
        }
    })
}

// 刷新表格数据
const refreshTable = () => {
  GetProducetion()
  ElMessage.success('数据已刷新')
}

// 处理分页变化
const handlePageChange = (newPage: number) => {
  page.Index = newPage
  GetProducetion()
}

// 卡片点击事件
const handleCardClick = (item: any) => {
  ElMessage.info(`查看${item.label}详情`)
}

// 快捷操作点击事件
const handleQuickAction = (item: any) => {
  router.push({ path: item.label.toLowerCase() })
  ElMessage.success(`执行${item.label}操作`)
  
  
}

// 获取进度条颜色
const getProgressColor = (ratio: number) => {
  if (ratio >= 0.8) return '#52c414'
  if (ratio >= 0.5) return '#faad14'
  return '#f5222d'
}

// 任务统计当前选择的时间周期
const currentTaskPeriod = ref<'7days' | '30days' | '1year'>('7days');
// 任务统计数据
const taskData = {
  '7days': {
    xAxis: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
    任务数: [17, 27, 10, 28, 13, 23, 8]
  },
  '30days': {
    xAxis: Array.from({ length: 30 }, (_, i) => i + 1),
    任务数: [21, 17, 11, 14, 12, 21, 23, 21, 17, 21, 21, 21, 27, 21, 17, 23, 13, 21, 28, 21, 21, 17, 13, 21, 28, 21, 17, 13, 21, 21]
  },
  '1year': {
    xAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    任务数: [11, 17, 21, 23, 17, 17, 25, 21, 17, 27, 23, 21]
  }
};
// 更新任务统计图表的方法
const updateTaskChart = (period: '7days' | '30days' | '1year') => {
  currentTaskPeriod.value = period;
  const data = taskData[period];

  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: data.xAxis
    },
    yAxis: { type: 'value' },
    series: [{
      name: '任务数',
      type: 'bar',
      data: data.任务数,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#1890ff' },
          { offset: 1, color: '#40a9ff' }
        ])
      }
    }]
  };
  
  if (taskChart.value) {
    const chart = echarts.init(taskChart.value);
    chart.setOption(option);
  }
};

// 当前选择的时间周期
const currentPeriod = ref<'7days' | '30days' | '1year'>('7days');

// 模拟数据
const qualityData = {
  '7days': {
    xAxis: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
   合格: [17, 27, 10, 28, 13, 23, 8],
    不合格: [6, 5, 2, 8, 4, 7, 3]
  },
  '30days': {
    xAxis: Array.from({ length: 30 }, (_, i) => i + 1),
    合格: [21, 17, 11, 14, 12, 21, 23, 21, 17, 21, 21, 21, 27, 21, 17, 23, 13, 21, 28, 21, 21, 17, 13, 21, 28, 21, 17, 13, 21, 21],
    不合格: [4, 3, 2, 3, 4, 5, 6, 4, 3, 5, 4, 3, 5, 4, 3, 5, 4, 3, 5, 4, 3, 5, 4, 3, 5, 4, 3, 5, 4, 5]
  },
  '1year': {
    xAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    合格: [11, 17, 21, 23, 17, 17, 25, 21, 17, 27, 23, 21],
    不合格: [1, 4, 3, 5, 3, 1, 4, 1, 5, 8, 7, 5]
  }
};

// 更新图表的方法
const updateQualityChart = (period: '7days' | '30days' | '1year') => {
  currentPeriod.value = period;
  const data = qualityData[period];

  const option = {
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['合格', '不合格'],
      top: '5%'
    },
    xAxis: {
      type: 'category',
      data: data.xAxis
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '合格',
        type: 'bar',
        data: data.合格,
        itemStyle: { color: '#52c414' },
        barGap: 0
      },
      {
        name: '不合格',
        type: 'bar',
        data: data.不合格,
        itemStyle: { color: '#f5222d' }
      }
    ]
  };

  if (qualityChart.value) {
    const chart = echarts.init(qualityChart.value);
    chart.setOption(option);
  }
};

// 工序选择
const selectedProcess = ref('all')
// 更新工序图表
const updateProcessChart = () => {
  // 这里可以根据选择的工序更新图表
  initProcessChart()
}

// 挂载图表容器
const taskChart = ref<HTMLDivElement | null>(null);
const defectChart = ref<HTMLDivElement | null>(null);
const processChart = ref<HTMLDivElement | null>(null);
const qualityChart = ref<HTMLDivElement | null>(null);

// 初始化工序图表
const initProcessChart = () => {
  const processOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: '5%',
      left: 'center',
      textStyle: { fontSize: 12 }
    },
    series: [{
      name: '工序不合格率',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: true,
        position: 'outside',
        formatter: '{d}%',
        fontSize: 12,
        color: '#333'
      },
      labelLine: {
        show: true,
        length: 10,
        length2: 20
      },
      data: [
        { value: 18, name: '印花装饰', itemStyle: { color: '#4096ee' } },
        { value: 25, name: '退火处理', itemStyle: { color: '#f5222d' } },
        { value: 30, name: '高温固化', itemStyle: { color: '#faad14' } },
        { value: 20, name: '切割修边', itemStyle: { color: '#52c414' } },
        { value: 7, name: '原料配比与混合', itemStyle: { color: '#13c2c2' } }
      ]
    }]
  };
  if (processChart.value) {
    const chart = echarts.init(processChart.value);
    chart.setOption(processOption);
  }
}

onMounted(() => {
  // 任务统计柱状图
  updateTaskChart('7days');

  // 初始化工序图表
  initProcessChart();

  // 生产质量统计柱状图
  updateQualityChart('7days');
});

onMounted(()=>{
  GetProducetion()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
  font-family: 'Microsoft YaHei', sans-serif;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(120deg, #1890ff, #40a9ff);
  border-radius: 8px;
  color: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.header h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}
.header p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
  justify-content: center;
}
.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  text-align: center;
  transition: all 0.3s ease;
  cursor: pointer;
  width: 100%;
}
.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.15);
}
.card .icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  margin: 0 auto 15px;
}
.card .text span {
  font-size: 14px;
  color: #666;
}
.card .text strong {
  font-size: 24px;
  color: #333;
  display: block;
  margin-top: 5px;
}

.charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}
.chart-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.chart-header h3 {
  margin: 0;
  color: #333;
}
.chart-controls {
  display: flex;
  gap: 15px;
}
.chart-controls span {
  cursor: pointer;
  font-size: 12px;
  color: #999;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}
.chart-controls .active, .chart-controls span:hover {
  color: #1890ff;
  background-color: #e6f7ff;
  font-weight: bold;
}
.chart {
  width: 100%;
  height: 300px;
}

.progress-container {
  width: 100%;
  height: 24px;
  background-color: #f0f0f0;
  border-radius: 12px;
  overflow: hidden;
}
.progress-bar {
  height: 100%;
  color: #fff;
  text-align: center;
  line-height: 24px;
  font-size: 12px;
  font-weight: bold;
  min-width: 30px;
  transition: width 0.5s ease;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.quick-access {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-top: 20px;
}
.quick-access h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}
.icons {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}
.icon-box {
  text-align: center;
  padding: 15px 10px;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}
.icon-box:hover {
  background: #f5f5f5;
  transform: translateY(-3px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.icon-box .icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  margin: 0 auto 10px;
}
.icon-box .label {
  font-size: 12px;
  color: #333;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts {
    grid-template-columns: 1fr;
  }
  
  .cards {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }
  
  .header {
    padding: 15px;
  }
  
  .chart-item {
    padding: 15px;
  }
  
  .icons {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* 图标支持 */
/* @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'); */
</style>
